 
/**
 * @file    hal_rs485.c
 * @author  Azolla (1228449928@qq.com)
 * @brief   led contorl PWM
 * @version 0.1
 * @date    2022-12-06
 * 
 * @copyright Copyright (c) 2022
 * */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/task.h"

#include "esp_system.h"
#include "nvs_flash.h"
#include "driver/uart.h"

#include "esp_log.h"
#include "sdkconfig.h"
 
#include "hal_uart.h"
#include "hal_rs485.h"

#define TAG "hal_rs485"

#define RS485_UART_PORT   UART_NUM_2
#define RS485_UART_SIZE   128

#define CONFIG_GPIO_RS485_TXD           (16)
#define CONFIG_GPIO_RS485_RXD           (18)
#define CONFIG_GPIO_RS485_RTS           (17)   // RE# / DE

uint8_t rs485_check_sum(uint8_t *data, uint8_t len)
{
    uint8_t check = 0x00;
    for (uint16_t i = 0; i < len; i++) {
        check += data[i];
    }
    return check;
}

void hal_rs485_write(const uint8_t *data, uint8_t len)
{
    hal_uart_write(RS485_UART_PORT, data, len);
}

 
void hal_rs485_init(uart_recv_callback_t cb_func)
{
    hal_uart_config_t uart = HAL_UART_CONFIG_DEFAULT(CONFIG_GPIO_RS485_TXD, CONFIG_GPIO_RS485_RXD, RS485_UART_PORT, 9600);
    uart.mode = UART_MODE_RS485_HALF_DUPLEX;
    uart.rts_pin = CONFIG_GPIO_RS485_RTS;
    uart.buff_size = RS485_UART_SIZE;
    hal_uart_driver_install(uart);
    hal_uart_recv_register_callback(uart.port, uart.buff_size, cb_func);  // 注册接收回调函数！
#if 0  // test...  
    while (1) {
        vTaskDelay(500);
        static uint8_t data = 0;
        data += 5;
        hal_rs485_write_bytes(RS485_SLAVE_ADDR, &data, 1);
    }
#endif    
}
